//获取应用实例
var app = getApp();
//获得

var MyRequest = require("../../utils/MyRequest.js");
var Global = require("../../Global.js");
var util = require('../../utils/util.js');
var Cart = require("../../LocalCart.js");

Page({
    data: {
        ProcuctCount: Cart.countCartNum(),
        CartList: Cart.geCartStorage(),
        TotalPrice: Cart.countCartPrice(),
        isFirst: false,
        coupon: "",
        defaultAddress: "",
        coupon: {
            name: "选择我的优惠券"
        },
        bz: '',
        IsShow: true
    },
    onShow: function () {
        this.Binder.bindDefaultAddress(this);
        this.Binder.bindCoupon(this);
    },
    bz_input: function (event) {
        this.setData({ bz: event.detail.value })
    },
    Presenter: {
        getDeliveredDate: function (that) {
            var data = { "action": "weekday" }
            MyRequest.MyGet("ActiveDay", that, that.Binder.bindDeliverDate, data)
        }
    },

    Binder: {
        bindData: function (that) {
            if (that.data.isFirst == false) {
                Cart.updateActiveIndex(that.data.DeliveredDate);
                that.setData({ isFirst: true });
            }
            that.setData({
                CartList: Cart.geCartStorage(),
                ProcuctCount: Cart.countCartNum(),
                TotalPrice: Cart.countCartPrice()
            });
        },
        bindCoupon: function (that) {
            var coupon = Cart.getCouponStorage();
            if (coupon) {
                that.setData({
                    coupon: coupon
                });
            } else {
                that.setData({
                    coupon: {
                        name: "选择我的优惠券"
                    }
                });
            }
        },
        bindTimeQuantum: function (that) {
            var timeQuantum = new Array();
            timeQuantum.push({ time: "08:00~08:15" });
            timeQuantum.push({ time: "08:15~08:30" });
            timeQuantum.push({ time: "08:30~08:45" });
            timeQuantum.push({ time: "08:45~09:00" });
            timeQuantum.push({ time: "09:00~09:15" });
            timeQuantum.push({ time: "09:15~09:30" });
            that.setData({
                TimeQuantum: timeQuantum,
                TimeQuantumIndex: 0
            });
        },
        bindDefaultAddress: function (that) {
            var address = Cart.getAddressStorage();
            that.setData({
                defaultAddress: address
            });
        },
        bindDeliverDate: function (result, that) {
            var dateList = new Array();
            var data = result.data.data;
            for (var i = 0; i < data.length; i++) {
                var item = data[i];
                var week = item.wday;
                var w = "";
                switch (week) {
                    case 2:
                        w = "周一";
                        break;
                    case 3:
                        w = "周二";
                        break;
                    case 4:
                        w = "周三";
                        break;
                    case 5:
                        w = "周四";
                        break;
                    case 6:
                        w = "周五";
                        break;
                    case 7:
                        w = "周六";
                        break;
                }
                item.detailDate = item.wdate + " [" + w + "]";
                item.week = w;
                if (item.state == "2" || item.state == 2) {
                    dateList.push(item);
                } else if (item.state == "3" || item.state == 3) {
                    dateList.push(item);
                }
            }
            that.setData({
                DeliveredDate: dateList
            });
            that.Binder.bindData(that);
        },
        bindOrder: function (result, that) {
            var data = result.data.data;
            var parameter = "?";
            parameter += "accountMoney=" + data.accountMoney + "&";
            parameter += "freePrice=" + data.freePrice + "&";
            parameter += "goodsCount=" + data.goodsCount + "&";
            parameter += "orderId=" + data.orderId + "&";
            parameter += "orderNo=" + data.orderNo + "&";
            parameter += "orderTime=" + data.orderTime + "&";
            parameter += "totalPrice=" + data.totalPrice;
            Cart.clearCartStorage();
            wx.redirectTo({
                url: '/pages/pay/pay' + parameter,
            });
        }
    },
    onLoad: function (options) {
        if (Cart.countCartNum() == 0) {
            this.setData({
                IsShow: false
            });
        }
        Cart.setCouponStorage("");
        this.Binder.bindTimeQuantum(this);
        this.Presenter.getDeliveredDate(this);
    },
    onPullDownRefresh: function () {
        wx.stopPullDownRefresh();
    },
    onCartAdd: function (event) {
        var product = event.target.dataset.product;
        Cart.updateCartNum(product, 1);
        this.setData({
            CartList: Cart.geCartStorage(),
            ProcuctCount: Cart.countCartNum(),
            TotalPrice: Cart.countCartPrice()
        });
    },
    onCartSub: function (event) {
        var product = event.target.dataset.product;
        Cart.updateCartNum(product, 2);
        this.setData({
            CartList: Cart.geCartStorage(),
            ProcuctCount: Cart.countCartNum(),
            TotalPrice: Cart.countCartPrice()
        });
    },
    onTimeQuantum: function (event) {
        var index = event.detail.value;
        this.setData({ TimeQuantumIndex: index });
    },
    onDeliveredDateChange: function (event) {
        var curProduct = event.target.dataset.product;
        var index = parseInt(event.detail.value);
        var curDate = this.data.DeliveredDate[index];
        Cart.updateDate(curProduct, curDate, index);
        this.Binder.bindData(this);
    },
    toAddress: function () {
        if (!Global.getUserStorage()) {
            wx.navigateTo({
                url: '/pages/login/login'
            })
        } else {
            var params = "?isFrom=cart";
            wx.navigateTo({
                url: '/pages/address/address' + params
            })
        }
    },
    toPay: function () {
        if (!Global.getUserStorage()) {
            wx.navigateTo({
                url: '/pages/login/login'
            })
        }
        if (!this.data.defaultAddress) {
            wx.showToast({ title: "请选择收货地址", icon: 'success', duration: 1000 });
            return;
        }
        console.log("订单提交");
        console.log(this.CartList);
        if (!this.CartList || this.CartList.length <= 0) {
            wx.showToast({ title: "请先选择商品", icon: 'success', duration: 1000 });
            return;
        }
        var coupon = this.data.coupon;
        var shopData = Cart.getOrderList();
        var orderInfo = {
            "address": this.data.defaultAddress.id,
            "mark": this.data.bz,
            "mobile": Global.getUserStorage().mobile,
            "time": this.data.TimeQuantum[this.data.TimeQuantumIndex].time,
            "userId": Global.getUserStorage().id,
            "shopData": shopData
        };
        if (coupon) {
            orderInfo.couponId = coupon.couponId;
            orderInfo.couponUserId = coupon.id;
        }
        var newOrderInfo = JSON.stringify(orderInfo);
        newOrderInfo.replace('\"', "'");
        var data = {
            action: "packages",
            platform: Global.getPlatform(),
            userId: Global.getUserStorage().id,
            cityId: this.data.defaultAddress.cityId,
            areaId: this.data.defaultAddress.areaId,
            orderInfo: newOrderInfo
        };
        MyRequest.MyPostWithToast("OrderSubmit", this, this.Binder.bindOrder, data);
    },
    toCoupon: function () {
        var params = "?from=cart&TotalPrice=" + this.data.TotalPrice;
        wx.navigateTo({
            url: '/pages/coupon/coupon' + params
        });
    }

})